package thread;

import sun.font.DelegatingShape;

public class MyBlockingQueue {
    private String[] elems = null;
    private int head = 0;
    private int tail = 0;
    private int size = 0;
    Object locker = new Object();

    public MyBlockingQueue(int capacity) {
        elems = new String[capacity];
    }

    public void put(String elem) throws InterruptedException {
        synchronized (locker) {
            while (size >= elem.length()) {
                //队列满了就阻塞等待
                locker.wait();
            }

            elems[tail] = elem;
            tail++;
            if(tail >= elems.length) {
                tail = 0;
            }
            size++;

            //入队列后唤醒
            locker.notify();
        }
    }

    public String take() throws InterruptedException {
        String elem = null;
        synchronized (locker) {
            while (size == 0) {
                //队列为空,阻塞等待
                locker.wait();
            }

            elem = elems[head];
            head++;
            if(head >= elems.length) {
                head=0;
            }
            size--;

            //元素出队列后, 唤醒
            locker.notify();;
        }
        return elem;
    }
}
